<template>
	<cl-dialog v-model="visible" :title="`开处方 - ${formData.name} ${formData.phone}`" width="600px">
        <el-form ref="form" :rules="rules" :model="formData" label-width="100px">
            <el-form-item label="客户分层" prop="layer">
                <cl-select
                    v-model="formData.layer"
                    placeholder="客户分层"
                    :options="dict.get('Layer')"
                    :tree="true"
                />
            </el-form-item>
			<el-form-item label="客户分类" prop="category">
                <cl-select
                    v-model="formData.category"
                    placeholder="客户分类"
                    :options="dict.get('UserCategory')"
                    :tree="true"
                />
            </el-form-item>
            <el-form-item label="推荐方案" prop="suggestPlan">
                <el-input type="textarea" placeholder="请输入推荐方案" v-model="formData.suggestPlan" />
            </el-form-item>
			<el-form-item label="依从性" prop="compliance">
				<cl-select v-model="formData.compliance" :tree="true" :checkStrictly="true" :options="dict.get('Compliance')" />
			</el-form-item>
            <el-form-item label="入组" prop="inGroup">
				<cl-select v-model="formData.inGroup" :tree="true" :checkStrictly="true" :options="dict.get('inGroup')" />
			</el-form-item>
			<el-form-item label="决策人" prop="decisionPerson">
				<cl-select v-model="formData.decisionPerson" placeholder="请选择是否到场" :options="options.decisionPerson" />
			</el-form-item>
			<el-form-item label="验光师" prop="optometrist">
                <cl-select
                    v-model="formData.optometrist"
                    placeholder="验光师"
					:options="options.optometristList"
                />
            </el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button type="primary" @click="handleSave">确定</el-button>
		</template>
	</cl-dialog>
</template>

<script lang="ts" setup>
import { useCrud, useTable, useUpsert, useSearch } from "@cool-vue/crud";
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useCool } from '/@/cool';
import { useDict } from '/$/dict';
import { ElMessage } from 'element-plus';
import { useBase } from '/$/base';

const { service } = useCool();
const { dict } = useDict();
const { user } = useBase();

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	studentId: {
		type: [Number, String],
		default: 0
	},
	appointObj: {
		type: Object,
		default: () => ({})
	}
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = computed({
	get: () => props.modelValue,
	set: val => emit('update:modelValue', val)
});
const salesList = ref([]);
const formData = reactive({
	id: 0,
	name: '',
	phone: '',
	inGroup: '',
	layer: '',
	categroy: '',
	suggestPlan: '',
	compliance: '',
	visitCount: 0,
	lastVisitDate: '',
	lastVisitAppointmentId: 0,
	decisionPerson: 0,
	optometrist: 0,
});
const prescriptionData = computed(() => ({
	id: 0,
	inGroup: '',
	layer: '',
	category: '',
	suggestPlan: '',
	compliance: '',
	decisionPerson: 0,
	studentId: 0,
	appointmentId: 0,
	optometrist: 0,
}));
const options = reactive({
	decisionPerson: [
		{ label: '未到场', value: 0 },
		{ label: '到场', value: 1 }
	],
	optometristList: []
});
const appointObj = ref({});
// 初始化销售列表和学员信息
async function initData() {
	try {
		// 获取销售列表
		const salesRes = await service.base.sys.user.getSelectList();
		if (salesRes) {
			salesList.value = salesRes;
		}

		// 获取学员信息
		if (props.studentId) {
			const studentRes = await service.student.student.info({
				id: props.studentId
			});

			Object.assign(formData, {
				id: studentRes.id,
				name: studentRes.name,
				phone: studentRes.phone,
				inGroup: studentRes.inGroup,
				layer: studentRes.layer,
				suggestPlan: studentRes.suggestPlan,
				compliance: studentRes.compliance,
				visitCount: studentRes.visitCount,
				lastVisitDate: studentRes.lastVisitDate,
				lastVisitAppointmentId: studentRes.lastVisitAppointmentId,
			});
		}
		if (props.appointObj) {
			appointObj.value = props.appointObj;
			// 获取处方信息
			const prescription = await service.student.prescription.list({
				appointmentId: props.appointObj.id
			});
			console.log('prescription', prescription);
			if (prescription && prescription.length > 0) {
				prescriptionData.value.id = prescription[0].id || 0;
				Object.assign(formData, {
					layer: prescription[0].layer,
					category: prescription[0].category,
					suggestPlan: prescription[0].suggestPlan,
					compliance: prescription[0].compliance,
					inGroup: prescription[0].inGroup,
					decisionPerson: prescription[0].decisionPerson,
					optometrist: prescription[0].optometrist,
				});
			}
		}
	} catch (error) {
		console.error('初始化数据失败:', error);
	}
}
const form = ref(null);
const rules = reactive({
    layer: [
        { required: true, message: '请选择客户分层', trigger: 'change' }
    ],
	category: [
        { required: true, message: '请选择客户分类', trigger: 'change' }
    ],
    suggestPlan: [
        { required: true, message: '请输入推荐方案', trigger: 'blur' }
    ],
    compliance: [
        { required: true, message: '请选择依从性', trigger: 'change' }
    ],
    inGroup: [
        { required: true, message: '请选择入组情况', trigger: 'change' }
    ],
	decisionPerson: [
        { required: true, message: '请选择决策人', trigger: 'change' }
    ],
	optometrist: [
        { required: true, message: '请选择验光师', trigger: 'change' }
    ],
});
// 保存
async function handleSave() {
	if (!form.value) return;
	try {
        // 修改验证方式，直接使用 await
        await form.value.validate();
    } catch (error) {
        ElMessage.warning('请填写完整表单信息');
        return;
    }
	try {
		// 如果都填写了入组、推荐方案、依从性、客户分层，视为已就诊，则就诊次数+1
		if (formData.inGroup && formData.suggestPlan && formData.compliance && formData.layer) {
			formData.visitCount++;
			// 查看最近就诊日期是否比当前日期早，如果早，则更新最近就诊日期，并且更新预约状态
			if (appointObj.value) {
				if (formData.lastVisitDate) {
					if (new Date(formData.lastVisitDate) < new Date(appointObj.value.appointmentTime)) {
						formData.lastVisitDate = appointObj.value.appointmentTime;
						formData.lastVisitAppointmentId = appointObj.value.id;
					}
				} else {
					formData.lastVisitDate = appointObj.value.appointmentTime;
					formData.lastVisitAppointmentId = appointObj.value.id;
				}
				
				appointObj.value.comeType = 2;
				await service.appointment.info.update(appointObj.value);

				prescriptionData.value.appointmentId = appointObj.value.id;
				prescriptionData.value.studentId = formData.id;
				prescriptionData.value.inGroup = formData.inGroup;
				prescriptionData.value.layer = formData.layer;
				prescriptionData.value.category = formData.category;
				prescriptionData.value.suggestPlan = formData.suggestPlan;
				prescriptionData.value.compliance = formData.compliance;
				prescriptionData.value.decisionPerson = formData.decisionPerson;
				prescriptionData.value.optometrist = formData.optometrist;
				if (prescriptionData.value.id) {
					await service.student.prescription.update(prescriptionData.value);
				} else {
					await service.student.prescription.add(prescriptionData.value);
				}
			}
		} else {
			ElMessage.warning('请填写完整表单信息');
			return;
		}
		await service.student.student.update(formData);
		ElMessage.success('保存成功');
		visible.value = false;
		emit('success');
	} catch (error) {
		ElMessage.error('保存失败');
	}
}
onMounted(async () => {
	await getOptometristList();
})

// 获取验光师列表
async function getOptometristList() {
	try {
		const res = await service.base.sys.user.getSelectList({
			shop: user.info?.shop
		});
		if (res) {
			options.optometristList = res;
		}
	} catch (error) {
		console.error('获取验光师列表失败:', error);
	}
}

const handleCancel = () => {
	visible.value = false;
};

// 监听弹窗显示状态，显示时初始化数据
watch(
	() => visible.value,
	val => {
		if (val && props.studentId) {
			initData();
		}
	}
);

// 监听学员ID变化
watch(
	() => props.studentId,
	val => {
		if (visible.value && val) {
			initData();
		}
	}
);

defineExpose({
	formData
});
</script>
<style scoped>
.report-block {
	border: 1px solid #eee;
	padding: 10px;
	margin-bottom: 10px;
	border-radius: 4px;
}
</style>